<template>
  <div class="basic-info-page">
    <!-- 头部 -->
    <div class="header d-flex align-items-center">
      <router-link to="/login" class="text-dark">
        <i class="bi bi-chevron-left fs-4"></i>
      </router-link>
      <h5 class="mb-0 mx-auto">填写基本信息</h5>
    </div>

    <!-- 表单内容 -->
    <div class="form-container">
      <div class="form-group mb-3">
        <label class="form-label">姓名</label>
        <input
            type="text"
            class="form-control"
            v-model="form.realName"
            placeholder="请输入姓名"
        >
      </div>
      <!-- 考研年份 -->
      <div class="form-group mb-3">
        <label class="form-label">考研年份</label>
        <select class="form-select" v-model="form.userLevel">
          <option v-for="year in years" :key="year" :value="year">{{ year }}</option>
        </select>
      </div>
      <!-- 年龄 -->
      <div class="form-group mb-3">
        <label class="form-label">年龄</label>
        <input
            type="text"
            class="form-control"
            v-model="form.age"
            placeholder="请输入年龄"
        >
      </div>
      <!-- 性别 -->
      <div class="form-group mb-3">
        <label class="form-label">性别</label>
        <select class="form-select" v-model="form.sex">
          <option value="1">男</option>
          <option value="2">女</option>
        </select>
      </div>
      <!-- 出生日期 -->
      <div class="form-group mb-3">
        <label class="form-label">出生日期</label>
        <div>
          <date-picker
              v-model="form.birthDay"
              :format="'YYYY-MM-DD'"
          ></date-picker>
        </div>
      </div>
      <div class="form-group mb-3">
        <label class="form-label">是否允许老师监督学习</label>
        <div>
          <input type="radio" id="supervision" value="1" v-model="form.supervision" />
          <label for="supervisionYes">允许</label>
          <input type="radio" id="supervision" value="0" v-model="form.supervision" />
          <label for="supervisionNo">不允许</label>
        </div>
      </div>
      <!-- 目标专业 -->
      <div class="form-group mb-3">
        <label class="form-label">目标专业</label>
        <input
            type="text"
            class="form-control"
            v-model="form.targetMajor"
            placeholder="请输入目标专业"
        >
      </div>
      <!-- 目标院校 -->
      <div class="form-group mb-3">
        <label class="form-label">目标院校</label>
        <input
            type="text"
            class="form-control"
            v-model="form.targetUniversity"
            placeholder="请输入目标院校"
        >
      </div>
      <!-- 选择科目 -->
      <div class="form-group mb-3">
        <label class="form-label">选择科目</label>
        <button class="btn btn-primary" @click="openSubjectModal">选择科目</button>
        <div v-if="selectedSubjectName">已选择：{{ selectedSubjectName }}</div>
      </div>

      <!-- 科目选择弹窗 -->
      <div>
        <div class="modal fade" id="subjectModal" tabindex="-1" ref="subjectModal">
          <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title">选择考试科目</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
              </div>
              <div class="modal-body">
                <!-- 循环展示一级目录（科目） -->
                <!-- 循环展示一级目录（科目） -->
                <div v-for="firstLevel in subjectHierarchy" :key="firstLevel.categoryName" class="subject-category">
                  <h6 class="mb-3">{{ firstLevel.categoryName }}</h6>
                  <div class="subject-buttons horizontal-subjects">
                    <!-- 循环展示每个一级科目下的二级选项 -->
                    <div v-for="option in firstLevel.childrenList || []" :key="option.id">
                      <input
                          type="radio"
                          class="btn-check"
                          :name="firstLevel.categoryName"
                          :id="`${firstLevel.categoryName}-${option.id}`"
                          :value="option.id"
                          v-model="selectedSubjectIds[firstLevel.categoryName]"
                          @change="updateSelectedSubjectId(option.id,option.categoryName)"
                      >
                      <label
                          class="btn btn-outline-primary"
                          :for="`${firstLevel.categoryName}-${option.id}`"
                      >
                        {{ option.categoryName }}
                      </label>
                    </div>
                  </div>
                  <br/>
                </div>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" @click="confirmSubjectSelection">确定</button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 提交按钮 -->
      <button class="btn btn-primary w-100 mb-3" @click="submitForm">提交</button>
      <!-- 跳过按钮 -->
      <button class="btn btn-secondary w-100 mb-3" @click="skipForm">跳过</button>
    </div>
  </div>
</template>

<script>
import DatePicker from 'vue3-datepicker';
import http from '@/router/http';
import {Modal} from "bootstrap";
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import router from "@/router";
dayjs.extend(utc);
export default {
  name: 'BasicInfoView',
  components: {
    DatePicker
  },
  mounted() {
    this.modal = new Modal(this.$refs.subjectModal);
    this.modal.hide();
    this.setSubjectInfo()
  },
  data() {
    return {
      form: {
        realName: '',
        userLevel: '',
        age: '',
        sex: '',
        birthDay: '',
        supervision: '',
        targetMajor: '',
        targetUniversity: '',
      },
      years: [
        '2025',
        '2026',
        '2027',
        '2028',
        '2029',
        '2030',
        '2031',
        '2032',
        '2033',
        '2034',
        '2035',
        '2036'
      ],
      userId: null,
      selectedSubjectName: null,
      selectedSubjectIdsStr: null,
      loading: false,
      modal: null,
      subjectHierarchy: [],
      selectedSubjects: [], // 存储选择的科目信息（包含名称和id）
      selectedSubjectIds: {} // 存储每个一级科目下选中的科目id

    };
  },
  methods: {
    updateSelectedSubjectId(id, name,firstLevelName) {
      this.selectedSubjectIds[firstLevelName] = id;
    },
    openSubjectModal() {
      this.loading = true;
      this.modal.show();
    },
    async setSubjectInfo() {
      this.loading = true;
      await http.get('/admin/dataDictionary/findTreeByCondition')
          .then(response => {
            if (response.data.code === 1) {
              this.subjectHierarchy = [];
              response.data.response.forEach(item => {
                this.subjectHierarchy.push(item);
              });
              this.loading = false;
            }
          })
          .catch(error => {
            console.error('获取科目层级数据出现异常：', error);
            this.loading = false;
          });
    },
    closeSubjectModal() {
      this.modal.hide();
    },
    confirmSubjectSelection() {
      this.selectedSubjects = [];
      this.selectedSubjectName =  null;
      this.selectedSubjectIdsStr = null;
      // 遍历每个一级科目，找到选中的二级科目
      for (const firstLevel of this.subjectHierarchy) {
        const selectedId = this.selectedSubjectIds[firstLevel.categoryName];
        if (selectedId) {
          const selectedOption = (firstLevel.childrenList || []).find(option => option.id === selectedId);
          if (selectedOption) {
            this.selectedSubjects.push({
              id: selectedOption.id,
              name: selectedOption.categoryName
            });
          }
        }
      }
      this.selectedSubjectName = this.selectedSubjects.map(subject => subject.name).join(', ');
      this.selectedSubjectIdsStr = this.selectedSubjects.map(subject => subject.id).join(',');
      console.log('选择的科目信息：', this.selectedSubjects);
      this.modal.hide();
    },
    async submitForm() {
      try {
        if(!this.$route.query.userId){
          alert('用户不存在')
          return;
        }
        const  requestData = {
          userId: this.$route.query.userId,
          realName: this.form.realName,
          userLevel: this.form.userLevel,
          targetMajor: this.form.targetMajor,
          targetUniversity: this.form.targetUniversity,
          age: this.form.age,
          sex: this.form.sex,
          supervision: this.form.supervision,
          birthDay: this.form.birthDay!== "" && this.form.birthDay !== null ? dayjs(this.form.birthDay).utc().local().format('YYYY-MM-DD'):null,
          optSubject: this.selectedSubjectIdsStr,
        };
        const response = await http.post('/student/user/editAfterRegister', requestData);
        if (response.status === 200 && response.data.code === 1) {
          alert('个人信息保存成功');
          //直接登录接口登录成功
          this.login();
          //this.$router.push('/'); // 保存成功后跳转到个人资料页面
        }else{
          alert(response.data.message)
        }
      } catch (error) {
        console.error('保存个人信息失败:', error);
      }
    },
    skipForm() {
      //直接调用登录接口登录成功
      this.login();
    },
    async login(){
      try {
        const loginForm = {
          username: this.$route.query.userName,
          password: this.$route.query.password
        }
        const response = await http.post('/user/login', loginForm);
        const data = await response.data
        if (response.status === 200 && data.code === 1) {
          localStorage.setItem('token', data.response.token)
          localStorage.setItem('userId', data.response.userId);
          localStorage.setItem('role', data.response.role)
          if (data.response.role === 1) {
            router.push('/english')
          } else if (data.response.role === 3) {
            router.push('/groups')
          }
        } else {
         alert(data.message || '用户名或密码错误')
        }
      } catch (error) {
        console.error(error)
        alert('网络错误，请稍后重试');
      }
    }
  }
};
</script>

<style scoped>
/* 可以在这里添加针对radio按钮的样式调整，比如间距、大小等 */
label {
  margin-right: 10px;
}

.basic-info-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  padding: 15px;
  background: white;
  position: sticky;
  top: 0;
  z-index: 1000;
}

.form-container {
  padding: 20px;
}
.horizontal-subjects {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
</style>